use crate::utils::get_app;
use anyhow::Result;
use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::Manager;

pub fn tray_setup() -> Result<()> {
    let app_handle = get_app()?;

    // 取消关闭事件, 默认最小化窗口
    app_handle
        .get_window("main")
        .unwrap()
        .on_window_event(|event| {
            let app_handle = get_app().unwrap();
            if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                api.prevent_close();
                app_handle
                    .clone()
                    .get_window("main")
                    .unwrap()
                    .hide()
                    .unwrap();
            }
        });

    // 右键菜单
    let quit_i = MenuItem::with_id(&app_handle, "quit", "Quit", true, None::<&str>)?;
    let menu = Menu::with_items(&app_handle, &[&quit_i])?;

    let tray = TrayIconBuilder::new()
        .icon(app_handle.default_window_icon().unwrap().clone())
        .menu(&menu)
        .menu_on_left_click(false)
        .on_menu_event(|app, event| match event.id.as_ref() {
            "quit" => {
                app.exit(0);
            }
            _ => {}
        })
        .on_tray_icon_event(|tray, event| match event {
            TrayIconEvent::Click {
                button: MouseButton::Left,
                button_state: MouseButtonState::Up,
                ..
            } => {
                // in this example, let's show and focus the main window when the tray is clicked
                let app = tray.app_handle();
                if let Some(window) = app.get_webview_window("main") {
                    let _ = window.show();
                    let _ = window.unminimize();
                    let _ = window.set_focus();
                }
            }
            _ => {}
        })
        .build(&app_handle)?;
    Ok(())
}
